package com.winit.openapi.isp.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.isp.ISPOrderExceptionHandleService;
import com.winit.oms.spi.isp.command.CreateISPOrderExceptionHandleCommand;
import com.winit.oms.spi.isp.command.ISPOrderExceptionHandleSearchCommand;
import com.winit.oms.spi.isp.command.ISPOrderExceptionYWHandleCommand;
import com.winit.oms.spi.isp.vo.ISPOrderExceptionHandleVo;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * 
 * ISP异常件处理Controller
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * kang.wang 	1.0  		2016年4月25日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
public class ISPOrderExpHandleController extends BaseController {
    
    @Resource
    private ISPOrderExceptionHandleService iSPOrderExceptionHandleService;

    @RequestMapping(value = "/isp/order/expHandleList")
    public String expHandleList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        
        Object obj = requestMsg.getData();

        ISPOrderExceptionHandleSearchCommand command = null;

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validSearchExpHandle(json);
            command = buildSearchExpHandleCommand(json);
            Searchable<?> searchable = buildSearchPageParams(json);
            command.setSearchable(searchable);
        } else if (obj == null || StringUtils.isBlank(obj.toString())) {
            Searchable<?> searchable = buildSearchPageParams(null);
            command = new ISPOrderExceptionHandleSearchCommand();
            command.setSearchable(searchable);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        

        // 调用接口分页查询订单
        Page<ISPOrderExceptionHandleVo> pagelist = iSPOrderExceptionHandleService.getISPExpectionOrderByCondition(command);
        if (pagelist != null) {
            Map<String, Object> pageMap = new HashMap<String, Object>();
            pageMap.put("pageNo", pagelist.getPageable().getPageNumber());
            pageMap.put("pageSize", pagelist.getPageable().getPageSize());
            pageMap.put("totalCount", pagelist.getTotalElements());

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", pagelist.getContent());
            data.put("pageParams", pageMap);
            responseMsg.setData(data);
        }
        
        return SUCCESS;
    }

    private void validSearchExpHandle(JSONObject json) {
        // orderNo
        ValidateUtil.validMaxLength(json, "orderNo", 60);
        // expressNo
        ValidateUtil.validMaxLength(json, "expressNo", 60);
        // winitProductCode
        ValidateUtil.validMaxLength(json, "winitProductCode", 60);
        // orderDateStart
        ValidateUtil.validDateString(json, "orderDateStart", DateUtil.SIMPLE_DATE_STRING);
        // orderDateEnd
        ValidateUtil.validDateString(json, "orderDateEnd", DateUtil.SIMPLE_DATE_STRING);
        ValidateUtil.validDateBefore(json, "orderDateStart", "orderDateEnd");

        // pageParams
        if (json.containsKey("pageParams")) {
            Object obj = json.get("pageParams");
            if (obj instanceof JSONObject) {
                JSONObject pageParams = (JSONObject) obj;
                // pageNo
                ValidateUtil.validInteger(pageParams, "pageNo");

                // pageSize
                ValidateUtil.validInteger(pageParams, "pageSize");

                if (isExistValue(pageParams, "pageNo")) {
                    int pageNo = pageParams.getInteger("pageNo");
                    if (pageNo < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                    }
                }
                if (isExistValue(pageParams, "pageSize")) {
                    int pageSize = pageParams.getInteger("pageSize");
                    if (pageSize < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                    }
                }
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageParams");
            }
        }
    }
    
    private ISPOrderExceptionHandleSearchCommand buildSearchExpHandleCommand(JSONObject json) {
        ISPOrderExceptionHandleSearchCommand command = new ISPOrderExceptionHandleSearchCommand();
        // orderNo
        if (json.containsKey("orderNo")) {
            command.setOrderNo(json.getString("orderNo"));
        }
        // expressNo
        if (json.containsKey("expressNo")) {
            command.setExpressNo(json.getString("expressNo"));;
        }
        // winitProductCode
        if (json.containsKey("winitProductCode")) {
            command.setWinitProductCode(json.getString("winitProductCode"));
        }

        // orderDateStart
        if (json.containsKey("orderDateStart")) {
            String orderDateStart = json.getString("orderDateStart");
            orderDateStart += " 00:00:00";
            Date from = DateUtil.parse2Date(orderDateStart, DateUtil.FULL_DATE_STRING);
            command.setDateFrom(from);
        }
        // orderDateEnd
        if (json.containsKey("orderDateEnd")) {
            String orderDateEnd = json.getString("orderDateEnd");
            orderDateEnd += " 23:59:59";
            Date to = DateUtil.parse2Date(orderDateEnd, DateUtil.FULL_DATE_STRING);
            command.setDateTo(to);
        }
        
        // productCatalogLv2
        if (json.containsKey("productCatalogLv2")) {
            command.setProductCatalogLv2(json.getString("productCatalogLv2"));
        }

        return command;
    }
    
    private Searchable<?> buildSearchPageParams(JSONObject json) {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        // pageParams
        if (isExistValue(json, "pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");

            if (ValidateUtil.isIntNumber(pageParams.getString("pageNo"))) {
                pageNo = pageParams.getInteger("pageNo");
                if (pageNo <= 0) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                }
            } else if (isExistValue(pageParams, "pageNo") && !ValidateUtil.isIntNumber(pageParams.getString("pageNo"))) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageNo");
            }

            if (ValidateUtil.isIntNumber(pageParams.getString("pageSize"))) {
                pageSize = pageParams.getInteger("pageSize");
                if (pageSize <= 0) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                }
            } else if (isExistValue(pageParams, "pageSize")
                       && !ValidateUtil.isIntNumber(pageParams.getString("pageSize"))) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageSize");
            }

        }
        Searchable<?> search = Searchable.newSearchable();
        search.setPage(pageNo, pageSize);
        
        //增加排序
        if (json.containsKey("sort") && json.containsKey("sortColumn")) {
            String sort = json.getString("sort");
            String sortColumn = json.getString("sortColumn");
            if(StringUtils.equalsIgnoreCase(sort, "asc")){
                search.addSort(new Sort(Direction.ASC, sortColumn));
            } else {
                search.addSort(new Sort(Direction.DESC, sortColumn));
            }
        } else {
            //给默认排序字段
            search.addSort(new Sort(Direction.DESC, "CREATED"));
        }
        
        return search;
    }
    
    /**
     * 燕文异常件接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/isp/order/exceptionOrder")
    public String exceptionOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validISPExceptionOrder(json);
          
            CreateISPOrderExceptionHandleCommand command = buildCreateISPOrderExceptionHandleCommand(json);
            command.setVendorCode("YW");
            iSPOrderExceptionHandleService.addISPOrderExceptionHandle(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    /**
     * 燕文异常件处理接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/isp/order/exceptionOrderHandle")
    public String exceptionOrderHandle(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validISPExceptionHandleOrder(json);
            ISPOrderExceptionYWHandleCommand command = bulidISPOrderExceptionYWHandleCommand(json);
            
            iSPOrderExceptionHandleService.updateExceptionOrderByYw(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    
    

    private ISPOrderExceptionYWHandleCommand bulidISPOrderExceptionYWHandleCommand(JSONObject json) {
        ISPOrderExceptionYWHandleCommand command = new ISPOrderExceptionYWHandleCommand();
        if (json.containsKey("orderList")) {
            JSONArray packageList = json.getJSONArray("orderList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                if (pack.containsKey("expressNo")) {
                    command.setExpressNo(pack.getString("expressNo"));
                }
                if (pack.containsKey("handleCode")) {
                    command.setHandleCode(pack.getString("handleCode"));
                }
                if (pack.containsKey("handleDate")) {
                    command.setHandleDate(pack.getDate("handleDate"));
                }
                if (pack.containsKey("remark")) {
                    command.setRemark(pack.getString("remark"));
                }
                if (pack.containsKey("returnType")) {
                    command.setReturnType(pack.getString("returnType"));
                }
                if (pack.containsKey("returnExpressNo")) {
                    command.setReturnExpressNo(pack.getString("returnExpressNo"));
                }
                if (pack.containsKey("returnName")) {
                    command.setReturnName(pack.getString("returnName"));
                }
                if (pack.containsKey("returnPhone")) {
                    command.setReturnPhone(pack.getString("returnPhone"));
                }
                if (pack.containsKey("returnWarehouse")) {
                    command.setReturnWarehouse(pack.getString("returnWarehouse"));
                }
                if (pack.containsKey("bigpackageNo")) {
                    command.setBigpackageNo(pack.getString("bigpackageNo"));
                }
                if (pack.containsKey("fileLink")) {
                    command.setFileLink(pack.getString("fileLink"));
                }
            }
        }
        return command;
    }

    private void validISPExceptionHandleOrder(JSONObject json) {
        if (json.containsKey("orderList")) {
            JSONArray packageList = json.getJSONArray("orderList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                ValidateUtil.validNotNull(pack, "expressNo");
                ValidateUtil.validNotNull(pack, "handleCode");
                ValidateUtil.validNotNull(pack, "handleDate");
                ValidateUtil.validMaxLength(pack, "expressNo", 60);
                ValidateUtil.validMaxLength(pack, "handleCode", 60);
                ValidateUtil.validDateString(pack, "handleDate", ValidateUtil.DATE_PATTERN_BASE);
                ValidateUtil.validMaxLength(pack, "remark", 200);
                ValidateUtil.validMaxLength(pack, "returnType", 10);
                
                ValidateUtil.validMaxLength(pack, "returnExpressNo", 60);
                ValidateUtil.validMaxLength(pack, "returnName", 60);
                ValidateUtil.validMaxLength(pack, "returnPhone", 60);
                ValidateUtil.validMaxLength(pack, "returnWarehouse", 50);
                ValidateUtil.validMaxLength(pack, "bigpackageNo", 50);
                ValidateUtil.validMaxLength(pack, "fileLink", 200);
                
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "orderList");
        }
        
    }

    private CreateISPOrderExceptionHandleCommand buildCreateISPOrderExceptionHandleCommand(JSONObject json) {
        CreateISPOrderExceptionHandleCommand command = new CreateISPOrderExceptionHandleCommand();
        if (json.containsKey("orderList")) {
            JSONArray packageList = json.getJSONArray("orderList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                if (pack.containsKey("orderCode")) {
                    command.setOrderNo(pack.getString("orderCode"));
                }
                if (pack.containsKey("expressNo")) {
                    command.setExpressNo(pack.getString("expressNo"));
                }
                if (pack.containsKey("expectionCode")) {
                    command.setExpectionCode(pack.getString("expectionCode"));
                }
                if (pack.containsKey("expectionDate")) {
                    command.setExpectionDate(pack.getDate("expectionDate"));
                }
                if (pack.containsKey("remark")) {
                    command.setRemark(pack.getString("remark"));
                }
                if (pack.containsKey("exceptionWarehouse")) {
                	command.setExceptionWarehouse(pack.getString("exceptionWarehouse"));
                }
            }
        }
        return command;
    }

    private void validISPExceptionOrder(JSONObject json) {
        if (json.containsKey("orderList")) {
            JSONArray packageList = json.getJSONArray("orderList");
            for (Object obj : packageList) {
                JSONObject pack = (JSONObject) obj;
                ValidateUtil.validNotNull(pack, "expressNo");
                ValidateUtil.validNotNull(pack, "expectionDate");
                ValidateUtil.validNotNull(pack, "expectionCode");
//                ValidateUtil.validNotNull(pack, "exceptionWarehouse");
                ValidateUtil.validMaxLength(pack, "expressNo", 60);
                ValidateUtil.validMaxLength(pack, "remark", 200);
                ValidateUtil.validMaxLength(pack, "orderCode", 60);
                ValidateUtil.validMaxLength(pack, "expectionCode", 10);
                ValidateUtil.validDateString(pack, "expectionDate", ValidateUtil.DATE_PATTERN_BASE);
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "orderList");
        }
    }
    
}
